package com.sfl.api_backend.MqConsumer;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sfl.api_backend.entity.*;
import com.sfl.api_backend.entity.pred.batchTaskPredResult;
import com.sfl.api_backend.service.*;
import com.sfl.api_backend.utils.RandomID;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author szc
 * @create 2023/3/1 13:32
 */
@Component
public class TaskResultConsumer {

    @Resource
    private ITaskResultService taskResultService;

    @Resource
    private ITaskService taskService;

    @Resource
    private ILabelsetsService labelsetsService;

    @Resource
    private IDatasetsService datasetsService;

    @Resource
    private ILabelsService labelsService;

    @Resource
    private IImgsService imgsService;

    private final String BATCH_TASK_RESULT_QUEUE = "batch_task_result_queue";

    private final String IVK_TASK_RESULT_QUEUE = "ivk_task_result_queue";

    private final String MODEL_UPDATE_RESULT = "model_update_result";


    /**
     * resutl = {'batch_task_id': batch_task.batch_task_id,  # 任务id
     *           'user_id': batch_task.user_id,  # 用户id
     *           'pred_log_out': pred_log_out,  # 推理日志
     *           'generate_log_out': generate_log_out,  # 生成模型日志
     *           'error_files': error_files,  # 不支持的文件
     *           'TheerDobj_path': TheerDobj_path,  # 生成的模型路径
     *           'orginal_format': orginal_format,  # 原始格式的推理结果
     *           'niigz_format_pred': os.path.join(batch_task.savePath, 'pred'),  # niigz格式的推理结果，前端展示用
     *           'niigz_format_convert_tmp': convert_tmp_path,  # niigz格式的转换结果，前端展示用
     *           'analysis_json': os.path.join(batch_task.savePath, 'analysis')}  # 数据分析json路径
     * */

    @RabbitListener(queues = BATCH_TASK_RESULT_QUEUE)
    public void batchTaskPredResultConsumer(String msg) {
        try {
            TaskResult taskResult = JSON.parseObject(msg, TaskResult.class);
            taskResult.setResultId(RandomID.getRandomID());
            Integer taskId = taskResult.getTaskId();
            Task task = taskService.getById(taskId);

            Labelsets labelsets = labelsetsService.getById(task.getLabelSetId());
            Datasets datasets = datasetsService.getById(labelsets.getImgsetId());

            List<Imgs> dataset2imgs = imgsService.list(
                    new LambdaQueryWrapper<>(Imgs.class)
                            .eq(Imgs::getImgsetId, datasets.getImgsetId())
            );

            List<Labels> saveLabels = new ArrayList<>();

            // 创建label
            for (Imgs img : dataset2imgs) {
                Labels labels = new Labels();
                labels.setLabelId(RandomID.getRandomID());
                labels.setLabelName(img.getImgName());
                labels.setUserId(task.getUserId());
                Path path = Path.of(taskResult.getOrginalFormat(), img.getImgName());
                labels.setLabelPath(path.toString());
                labels.setImgId(img.getImgId());
                labels.setCreateTime(LocalDateTime.now());
                labels.setLabelsetId(labelsets.getLabelsetId());
                Path path_nii = Path.of(taskResult.getNiigzFormatPred(), img.getImgName().split("\\.")[0] + ".nii.gz");
                labels.setNiiFormatPath(path_nii.toString());
                Path path_3d = Path.of(taskResult.getTheerDobjPath(), img.getImgName().split("\\.")[0]);
                labels.setTheerDobjPath(path_3d.toString());
                Path path_ana = Path.of(taskResult.getAnalysisPath(),  task.getLabelSetId().toString(), img.getImgName().split("\\.")[0] + ".json");
                labels.setAnalysisPath(path_ana.toString());
                saveLabels.add(labels);
            }
            labelsService.saveBatch(saveLabels);
            labelsets.setLabelsetStatistics(Path.of(taskResult.getAnalysisPath(), "GlobalStatistics.json").toString());
            labelsetsService.updateById(labelsets);

            taskResultService.save(taskResult);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }




}
